package com.starblink.store.manage.ui

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.DefaultDecoration
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.rocketreserver.fragment.BrandVOF
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.store.R
import com.starblink.store.databinding.ActivityManageStoreBinding
import com.starblink.store.manage.adapter.ManageBrandHolder
import com.starblink.store.manage.adapter.ManageStoresHolder

/**
 * 管理我的店铺/品牌列表
 */
@Route(path = RoutePage.Store.PAGE_MANAGE)
class ManageStoreActivity : BaseTVMActivity<ActivityManageStoreBinding, ManageStoreVM>() {

    @Autowired(name = RoutePage.Store.IS_BRAND)
    @JvmField
    var isBrandType: Boolean = false
    override fun initViewBinding(): ActivityManageStoreBinding =
        ActivityManageStoreBinding.inflate(layoutInflater)


    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.stores.value!!).apply {
            addVhDelegate {
                ManageBrandHolder(
                    it, viewModel.selectStores.value!!,
                ) { position, merchantWebVOF ->
                    changeItem(merchantWebVOF, position)
                }
            }
            addVhDelegate {
                ManageStoresHolder(
                    it, viewModel.selectStores.value!!,
                ) { position, merchantWebVOF ->
                    changeItem(merchantWebVOF, position)
                }
            }
        }
    }

    private fun changeItem(
        merchantWebVOF: Any,
        position: Int
    ) {
        if (viewModel.selectStores.value!!.contains(merchantWebVOF)) {
            viewModel.selectStores.value!!.remove(merchantWebVOF)
        } else {
            viewModel.selectStores.value!!.add(merchantWebVOF)
        }
        viewModel.selectStores.postValue(viewModel.selectStores.value)
        adapter.notifyItemChanged(position)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarBlackText()

        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        viewBinding.rv.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        viewBinding.rv.addItemDecoration(DefaultDecoration(this).apply {
            startVisible = true
            endVisible = true
            this.setDivider(12.dp2px())
        })
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.loadStores(isBrandType)
        }
        viewModel.loadStores(isBrandType)

        viewBinding.tvFollow.setOnClickListener {
            if (viewModel.selectStores.value!!.isNotEmpty()) {
                viewModel.unFollowStores(isBrandType)

                var ids = ""
                viewModel.selectStores.value!!.forEach {
                    if (it is MerchantWebVOF) {
                        if (ids.isEmpty()) {
                            ids = it.id
                        } else {
                            ids = "$ids,${it.id}"
                        }
                    } else if (it is BrandVOF) {
                        if (ids.isEmpty()) {
                            ids = it.brandId.toString()
                        } else {
                            ids = "$ids,${it.brandId.toString()}"
                        }
                    }
                }
                it.trackData(
                    element = SpmElementDef.StoreManageUnFollow,
                    page = SpmPageDef.StoresManagePage, onlyHit = true,
                    params = mapOf("ids" to ids),
                )
            }
        }
        viewBinding.empty.onBtnClick = {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.STORES.value)
            }
        }
        startObserve()
    }

    private fun startObserve() {
        viewModel.stores.observe(this) {
            if (viewModel.stores.value!!.isNotEmpty() && viewBinding.rv.adapter == null) {
                viewBinding.rv.adapter = adapter//单位px
            }
            adapter.notifyDataSetChanged()
            viewBinding.empty.visibleOrGone(it.isEmpty() && viewModel.loaded) {}
            viewBinding.group.visibleOrGone(it.isNotEmpty()) {}

            if (viewBinding.refresher.isLoading) {
                viewBinding.refresher.finishLoadMore()
            }
        }
        viewBinding.tvNum.text =
            "${resources.getString(com.starblink.basic.style.R.string.store_selected)} ${viewModel.selectStores.value!!.size} ${if (isBrandType) "Brands" else "Stores"}"
        viewModel.selectStores.observe(this) {
            viewBinding.tvNum.text =
                "${viewModel.selectStores.value!!.size} ${if (isBrandType) "Brands" else "Stores"} ${resources.getString(com.starblink.basic.style.R.string.store_selected)} "
            viewBinding.tvFollow.setBackgroundResource(if (viewModel.selectStores.value!!.isNotEmpty()) R.drawable.bg_btn_follow else R.drawable.bg_btn_unfollow)
            viewBinding.tvNum.setTextColor(color(if (viewModel.selectStores.value!!.isNotEmpty()) com.starblink.basic.style.R.color.gu_text_secondary else com.starblink.basic.style.R.color.gu_text_tertiary))
        }

        viewModel.mLoadActionLiveData.observe(this) {
            if (viewModel.mLoadActionLiveData.value == LoadAction(LoadAction.STATE_NO_DATA)) {
                viewBinding.empty.visibleOrGone(true) {
                }
                viewBinding.group.visibleOrGone(false) {
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.StoresManagePage)
    }

    override fun onPause() {
        pageDisappear(SpmPageDef.StoresManagePage)
        super.onPause()
    }
}